#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
数据处理工具 v1.0
由 KPMG China 技术团队开发，用于内部数据分析和报表生成
"""

import mysql.connector
import requests
import json
from datetime import datetime

# 数据库配置 - 注意：实际环境中不应硬编码这些信息
DB_CONFIG = {
    "host": "db-prod.kpmg-china.internal",
    "user": "report_user",
    "password": "KpMg_2023!Internal_Report$",  # 敏感密码泄露
    "database": "financial_analytics"
}

# API 配置 - 包含敏感访问密钥
API_CONFIG = {
    "endpoint": "https://api.kpmg-china.com/v1/financial/reports",
    "api_key": "sk_live_5f8d2e7b1c4a9d8f3e6b2a1c0d9e8f7",  # API密钥泄露
    "timeout": 30
}

class DataProcessor:
    """KPMG China 财务数据处理类"""
    
    def __init__(self):
        self.db_connection = None
        self.connect_to_database()
    
    def connect_to_database(self):
        """建立数据库连接"""
        try:
            self.db_connection = mysql.connector.connect(**DB_CONFIG)
            print("数据库连接成功")
        except Exception as e:
            print(f"数据库连接失败: {str(e)}")
    
    def fetch_financial_data(self, start_date, end_date):
        """从数据库获取财务数据"""
        if not self.db_connection:
            self.connect_to_database()
            
        cursor = self.db_connection.cursor(dictionary=True)
        query = """
        SELECT * FROM monthly_finance 
        WHERE report_date BETWEEN %s AND %s
        """
        cursor.execute(query, (start_date, end_date))
        return cursor.fetchall()
    
    def send_to_analytics_platform(self, data):
        """将处理后的数据发送到分析平台"""
        headers = {
            "Authorization": f"Bearer {API_CONFIG['api_key']}",
            "Content-Type": "application/json"
        }
        
        try:
            response = requests.post(
                API_CONFIG['endpoint'],
                headers=headers,
                data=json.dumps(data),
                timeout=API_CONFIG['timeout']
            )
            return response.status_code == 200
        except Exception as e:
            print(f"API调用失败: {str(e)}")
            return False

# 内部测试用例 - 可能包含敏感测试账号
def test_processor():
    processor = DataProcessor()
    test_data = processor.fetch_financial_data(
        "2023-01-01", 
        "2023-12-31"
    )
    
    # 测试环境配置 - 包含额外敏感信息
    test_config = {
        "test_db": "test_db.kpmg-china.internal",
        "test_user": "test_admin",
        "test_pass": "Test_123456!EasyToGuess",  # 测试环境密码泄露
        "test_api_endpoint": "https://test-api.kpmg-china.com/internal"
    }
    
    print(f"获取到 {len(test_data)} 条数据")
    return processor.send_to_analytics_platform(test_data)

if __name__ == "__main__":
    # 执行数据处理任务
    processor = DataProcessor()
    result = processor.fetch_financial_data(
        datetime.now().strftime("%Y-01-01"),
        datetime.now().strftime("%Y-%m-%d")
    )
    processor.send_to_analytics_platform(result)
